<?php
namespace app\index\controller;

use app\common\controller\Base;
use app\index\model\Logs;
use app\ux\Json as JsonUx;
use app\ux\UtilCurl;
use think\Config;
use think\Db;
use think\Session;

/**
 * 道具以及邮件发放类
 */

class Issue extends Base
{

    private $server_id; //服务器ID
    private $issue_type; //发放类型
    private $issue_content; //发放内容
    private $mail_title; //邮件标题
    private $mail_content; //邮件内容
    private $callback; //回调函数
    private $base_url; //基 地 址
    private $param; //拼接参数
    private $curl; //工具实例
    private $url; //请求地址
    /**
     * 控制器初始化
     * @return   void
     */
    protected function _initialize()
    {
        //基类授权
        //
        parent::_initialize();

        $this->base_url = "http://192.168.2.232:9998/?mid=20000&uid=0&mail=";
        $this->actionLog();
    }
    /**
     * 发放道具
     */
    public function issue()
    {

        $curl      = new UtilCurl;
        $this->url = $this->base_url . json_encode($this->param);

        //测试回调
        $output['success'] = true;
        $output['msg']     = $this->url;
        _callback($output);

        //保存发放请求返回信息

        $rtn = $curl->get($this->url);
        $this->saveReply($this->id, $rtn);

        $output = json_decode($rtn, true);

        if (0 == $output['code']) {
            $output['success'] = true;
        } else {
            $output['success'] = false;
        }
        $_REQUEST['callback'] = $this->callback;
        _callback($output);
    }
    /**
     * 记录发放日志
     */
    public function actionLog()
    {

        $user = Session::get('CURRENT_USER');
        $data = getReq();

        $param = $this->getCallback($data['param']);

        if ($this->checkSign($param)) {

            $data['param']       = $this->getParam($data['param']);
            $data['role_name']   = $user['role_name'];
            $data['staff_name']  = $user['cname'];
            $data['staff_id']    = $user['user'];
            $data['url']         = $this->base_url;
            $data['create_time'] = date("Y-m-d H:i:s");
            //dump($data);

            //记录发放日志
            $Logs = new Logs;
            $Logs->data($data);
            $Logs->save();

            //记录发放参数
            $param       = $this->param;
            $param['id'] = $Logs->id;
            $this->param = $param; //发放参数
            $this->id    = $Logs->id; //数据库记录ID

        } else {
            $output['success'] = false;
            $output['msg']     = '异常消息:数据签名验证失败';
            _callback($output);
        }
    }
    /**
     * 记录回调参数
     */
    public function getCallback($data)
    {
        //回调函数
        if (array_key_exists("callback", $data)) {
            $this->callback = $data["callback"];
            unset($data["callback"]);
            return $data;
        } else {
            $output['success'] = false;
            $output['msg']     = ('异常消息:callback下标不存在');
            _callback($output);
        }

    }
    /**
     * 获取密钥
     */
    public function getSecretById($app_id)
    {
        $arr = Config::get('app_secret');
        return array_key_exists($app_id, $arr) ? $arr[$app_id] : "";
    }
    /**
     * 获取签名
     */
    public function getSign($param)
    {
        if (array_key_exists('sign', $param)) {
            $rtn['sign'] = $param['sign'];
            unset($param['sign']);
            $rtn['param'] = $param;
            return $rtn;
        } else {
            $output['success'] = false;
            $output['msg']     = ('异常消息:sign下标不存在');
            _callback($output);
        }
    }
    /**
     * (参数)排序签名
     */
    public function signParam($param)
    {
        $keys = array_keys($param);
        asort($keys);
        $str = '';
        foreach ($keys as $v) {
            $str .= $v . '=' . $param[$v] . '&';
        }
        $str = substr($str, 0, -1);
        $str = $str . $this->app_secret;

        return md5($str);
    }
    /**
     * 验证签名
     */
    public function checkSign($param)
    {
        if (array_key_exists("app_id", $param)) {
            $this->app_id     = $param["app_id"];
            $this->app_secret = $this->getSecretById($this->app_id);

            $rtn = $this->getSign($param);

            return ($rtn['sign'] == $this->signParam($rtn['param']));

        } else {
            $output['success'] = false;
            $output['msg']     = ('异常消息:app_id下标不存在');
            _callback($output);
        }
    }

    /**
     * 解析发放请求
     * @param    [type] $param [description]
     * @return   [type]
     */
    private function getParam($param)
    {
        //玩家ID
        $user_id  = array_key_exists("id", $_REQUEST) ? (!empty($_REQUEST["id"]) ? explode(",", $_REQUEST["id"]) : []) : [];
        $nickname = array_key_exists("nickname", $_REQUEST) ? (!empty($_REQUEST["nickname"]) ? explode(",", $_REQUEST["nickname"]) : []) : [];

        $arr = [];

        //全局发放
        //
        if (2 == $param["issuetype"]) {

            $player = 0;

            //单个发放
            //
        } else if (1 == $param["issuetype"]) {

            if (!empty($user_id)) {

                $where['id'] = ['IN', $user_id];
                $temp        = Db::table('d_character')->where($where)->field('id')->select();

                if ($temp) {
                    $temp = array_column($temp, 'id');
                    $arr  = array_merge($arr, $temp);
                }
            }

            if (!empty($nickname)) {
                $map['nickname'] = ['IN', $nickname];
                $temp            = Db::table('d_character')->where($map)->field('id')->select();
                if ($temp) {
                    $temp = array_column($temp, 'id');
                    $arr  = array_merge($arr, $temp);
                    $arr  = array_unique($arr);
                }
            }

            //获取角色ID数组字符串
            $this->player = implode(";", $arr);
        }

        $this->param = [
            "server_id" => $param["serverid"],
            "title"     => $param["title"],
            "content"   => $param["content"],
            "player"    => $this->player,
            "prize"     => $this->getPrize($param["issuecontent"]),
        ];

        return JsonUx::json_encode_Unescaped($this->param);
    }
    /**
     * 发放道具ID拼接转换
     * @param array prize 二维数组
     * @return array 拼接数组
     */
    public function getPrize($prize)
    {
        $temp = json_decode($prize, true);

        if (!empty($temp)) {

            foreach ($temp as $key => $value) {
                $temp[$key] = $temp[$key]['id'] . "=" . $temp[$key]['num'];
            }
            return implode(";", $temp);

        } else {
            return '';
        }
    }
    /**
     * 保存发放请求返回信息
     * @param    int $id 日志ID
     * @param    string $msg 操作返回信息
     * @return   void
     */
    public function saveReply($id, $msg)
    {

        try {
            $log         = Logs::get($id);
            $log->result = $msg;
            $log->save();

        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

}
